package com.cah.game;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cah.library.UserFunctions;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LobbyFragment extends Fragment
{
	private String userKey;
	TextView lobbyHeader;
	LinearLayout currentGameLayout;
	MainActivity main;
	ArrayList<JSONObject> lobbyInfo;
	FragmentManager fragmentManager;
	boolean infoLoaded;
	
	static final int LOBBY_TASK_FRAGMENT = 0;
	static final String LOBBY_TASK_FRAGMENT_TAG = "lobby";
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		fragmentManager = getFragmentManager();
		
		LobbyInfoFragment liFragment = (LobbyInfoFragment)fragmentManager.findFragmentByTag(LOBBY_TASK_FRAGMENT_TAG);
		
		if(liFragment != null)
		{
			liFragment.setTargetFragment(this, LOBBY_TASK_FRAGMENT);
		}
	}
	
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		infoLoaded = false;
		main = (MainActivity) getActivity();
		userKey = main.getUserKey();
		lobbyHeader = (TextView)main.findViewById(R.id.lobbyHeader);
		currentGameLayout = (LinearLayout)main.findViewById(R.id.currentActiveGameLinearLayout);
		main.setTitle("Cards Against Humanity");
		main.actionBar.setDisplayHomeAsUpEnabled(false);
		main.historyBackVisible = false;
		main.historyForwardVisible = false;
		main.invalidateOptionsMenu();
		
		if(savedInstanceState == null)
		{
			LobbyInfoFragment liFragment = new LobbyInfoFragment();
			liFragment.setTask(new LobbyInfoProcess());
			liFragment.setTargetFragment(this, LOBBY_TASK_FRAGMENT);
			liFragment.show(fragmentManager, LOBBY_TASK_FRAGMENT_TAG);
		}
		else
		{
			ArrayList<String> lobbyInfoStrings = savedInstanceState.getStringArrayList("lobbyInfo");
			if(lobbyInfoStrings != null)
			{
				lobbyInfo = new ArrayList<JSONObject>();
				for(int i=0;i<lobbyInfoStrings.size();i++)
				{
					try
					{
						lobbyInfo.add(new JSONObject(lobbyInfoStrings.get(i)));
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
				
				try
				{
					if(lobbyInfo.get(0).getInt("success")==1 && lobbyInfo.get(1).getInt("success")==1)
					{
						setInfo();
					}
					else
					{
						TextView newTextView = new TextView(main);
						newTextView.setText("No current games.  Join one or create one.");
						currentGameLayout.addView(newTextView);
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}
		
	}
	
	public void onSaveInstanceState(Bundle outState)
	{
		if(infoLoaded)
		{
			ArrayList<String> lobbyInfoStrings = new ArrayList<String>();
			for(int i=0;i<lobbyInfo.size();i++)
			{
				lobbyInfoStrings.add(lobbyInfo.get(i).toString());
			}
			
			outState.putStringArrayList("lobbyInfo", lobbyInfoStrings);
		}
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		
		return inflater.inflate(R.layout.lobby, container, false);
	}
		
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if((requestCode == LOBBY_TASK_FRAGMENT) && (resultCode == Activity.RESULT_OK))
		{
			ArrayList<String> lobbyInfoStrings = data.getStringArrayListExtra("lobbyInfo");
			lobbyInfo = new ArrayList<JSONObject>();
			for(int i=0;i<lobbyInfoStrings.size();i++)
			{
				try
				{
					lobbyInfo.add(new JSONObject(lobbyInfoStrings.get(i)));
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
			
			try
			{
				if(lobbyInfo.get(0).getInt("success")==1 && lobbyInfo.get(1).getInt("success")==1)
				{
					setInfo();
				}
				else
				{
					TextView newTextView = new TextView(main);
					newTextView.setText("No current games.  Join one or create one.");
					currentGameLayout.addView(newTextView);
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			
		}
	}
	
	private void setInfo()
	{
		ArrayList<JSONObject> jsons = lobbyInfo;
		try
		{
			lobbyHeader.setText("Welcome " + jsons.get(0).getString(UserFunctions.KEY_VALUE) + "!");
			
			JSONArray value = jsons.get(1).getJSONArray("value");
			boolean even = true;
			
			for(int i=0;i<value.length();i++)
			{
				JSONObject currentGameJson = value.getJSONObject(i);
				final String currentGameKey = currentGameJson.getString("gameKey");
				final int currentGameStatus = currentGameJson.getInt("status");
				final int currentGameAlert = currentGameJson.getInt("alert");
				final String currentGameName = currentGameJson.getString("name");
				
				
				TextView currentGameTextView = new TextView(main);
				currentGameTextView.setClickable(true);
				currentGameTextView.setTextSize(20);
				int padding = main.pxToDp(5);
				currentGameTextView.setPadding(padding, padding, 0, padding);
				if(even)
				{
					currentGameTextView.setTextColor(getResources().getColor(R.color.white));
					currentGameTextView.setBackgroundColor(getResources().getColor(R.color.black));
				}
				else
				{
					currentGameTextView.setTextColor(getResources().getColor(R.color.black));
					currentGameTextView.setBackground(getResources().getDrawable(R.drawable.back));
				}
				even = !even;
				
				if(currentGameAlert == 1)
				{
					currentGameTextView.setShadowLayer(5, 5, 5, getResources().getColor(R.color.red));
				}
				else if(currentGameAlert == 2)
				{
					currentGameTextView.setShadowLayer(5, 5, 5, getResources().getColor(R.color.fuchsia));
				}
				
				currentGameTextView.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View arg0)
					{
						if(currentGameAlert == 1)
						{
							new ChangeAlertProcess().execute(currentGameKey);
						}
						
						main.startGameFragment(currentGameKey, currentGameStatus);
					}
				});
				currentGameTextView.setText(currentGameName);
				
				currentGameLayout.addView(currentGameTextView);
			}
			
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		
		infoLoaded = true;
	}
	
	private class LobbyInfoProcess extends AsyncTask<Void, Void, ArrayList<String>>
	{
		LobbyInfoFragment frag;
		
		void setFragment(LobbyInfoFragment f)
		{
			frag = f;
		}
		
		@Override
		protected ArrayList<String> doInBackground(Void... params)
		{
			ArrayList<String> jsons = new ArrayList<String>();
			UserFunctions uf = new UserFunctions(userKey);
			jsons.add(uf.getUsername().toString());
			jsons.add(uf.fetchCurrentGames().toString());
			return jsons;
		}
		
		@Override
		protected void onPostExecute(ArrayList<String> jsons)
		{
			if(frag==null)
			{
				return;
			}
			
			Intent data = new Intent();
			data.putStringArrayListExtra("lobbyInfo", jsons);
			frag.taskFinished(data);
		}
	}
	
	private class ChangeAlertProcess extends AsyncTask<String, Void, JSONObject>
	{

		@Override
		protected JSONObject doInBackground(String... params)
		{
			String currentGameKey = params[0];
			UserFunctions uf = new UserFunctions(userKey);
			return uf.setAlertToSeen(currentGameKey);
		}
		
	}
	
	public static class LobbyInfoFragment extends DialogFragment
	{
		LobbyInfoProcess task;
		
		public void setTask(LobbyInfoProcess t)
		{
			task = t;
			task.setFragment(this);
		}
		
		@Override
		public void onCreate(Bundle savedInstanceState)
		{
			super.onCreate(savedInstanceState);
			
			setRetainInstance(true);
			
			if(task != null)
			{
				task.execute();
			}
		}
		
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState)
		{
			ProgressDialog pdia = new ProgressDialog(getActivity());
			pdia.setMessage("Loading your games...");
			pdia.setCanceledOnTouchOutside(false);
			return pdia;
		}
		
		@Override
        public void onDestroyView()
        {
            if (getDialog() != null && getRetainInstance())
                getDialog().setDismissMessage(null);
            super.onDestroyView();
        }
		
		@Override
        public void onDismiss(DialogInterface dialog)
        {
            super.onDismiss(dialog);
            // If true, the thread is interrupted immediately, which may do bad things.
            // If false, it guarantees a result is never returned (onPostExecute() isn't called)
            // but you have to repeatedly call isCancelled() in your doInBackground()
            // function to check if it should exit. For some tasks that might not be feasible.
            if (task != null) {
                task.cancel(false);
            }

            // You don't really need this if you don't want.
            if (getTargetFragment() != null)
                getTargetFragment().onActivityResult(LOBBY_TASK_FRAGMENT, Activity.RESULT_CANCELED, null);
        }
		
		@Override
        public void onResume()
        {
            super.onResume();
            // This is a little hacky, but we will see if the task has finished while we weren't
            // in this activity, and then we can dismiss ourselves.
            if (task == null)
                dismiss();
        }
		
		// This is also called by the AsyncTask.
        public void taskFinished(Intent data)
        {
            // Make sure we check if it is resumed because we will crash if trying to dismiss the dialog
            // after the user has switched to another app.
            if (isResumed())
                dismiss();

            // If we aren't resumed, setting the task to null will allow us to dimiss ourselves in
            // onResume().
            task = null;

            // Tell the fragment that we are done.
            if (getTargetFragment() != null)
                getTargetFragment().onActivityResult(LOBBY_TASK_FRAGMENT, Activity.RESULT_OK, data);
        }
	}
}


